//globals
var getRegisteredMapToolsUrl = "map/tools/records";
var registerMapToolUrl 	= "map/tools/create";
var editMapToolUrl 		= "map/tools/update";
var deleteMapToolUrl 	= "map/tools/delete";
var descriptorDigestUrl = "map/tools/descriptor"; 

var gridCols = {set:false}, gridMultiSelect = 1, selArr = [];      

$(function() {
	emp.$("#grid-map-tool").jqGrid({
		url: getRegisteredMapToolsUrl,
		index:'id',
		datatype: 'json',
		mtype: 'GET',
		colNames:['Id', 'Name', 'Description', 'Icon Url', 'Display Name', 'Auto Launch', 'Hidden'],
		colModel:[
		          {name:'id', index:'id', width:55, editable:true, editrules:{required:true}, editoptions:{size:10},hidden:true, key:true},
		          {name: 'name', index: 'name', width:200, editable: true, editrules: {required: true}, editoptions: {size: 50}, cellattr: function(rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal;"'; }},
		          {name: 'descr', index: 'descr', width: 250, editable: true, editrules: {required: true}, editoptions: {size: 50}, cellattr: function(rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal;"'; }},
		          {name: 'iconUrl', index: 'iconUrl', width: 260, editable: true, editrules: {required: true}, editoptions: {size: 50}},
		      	  {name: 'displayName', index: 'displayName', width: 120, align:'center', editable: true, editrules: {required: true}, editoptions: {size: 50}}, 
		      	  {name: 'autoLaunch', index: 'autoLaunch', width: 80, edittype:"select", align:'center', editable: true, formatter: 'select', editoptions: {value:"true:True; false:False", dataInit: function(elem){emp.$(elem).width(90);}  }},
		      	  {name: 'hidden', index: 'hidden', width: 80, edittype:"select", editable: true, align:'center', formatter: 'select', editoptions: {value:"true:True; false:False", dataInit: function(elem){emp.$(elem).width(90);}  }} 			          
		],
		postData: {},
		rowNum:10,
		rowList:[10,20,40,60],
		height: 'auto',
		autowidth: false,
		width: 'auto',
		rownumbers: true,
		pager: '#pager2',
		sortname: 'name',
		viewrecords: true,
		sortorder: "asc",
		caption:"Map Tools Registration",
		emptyrecords: "Empty records",
		loadonce: false,
		shrinkToFit: true,
		altRows:true,
		altClass:'toolsAltRow',
		multiselect: gridMultiSelect > 0,
		multiselectWidth: 25,
		onSelectRow: rowSelectionHandler,      			
		onSelectAll: selectAllHandler,
		gridComplete: gridLoadInit3,                   
		
		loadComplete: function() {},
		jsonReader : {
			root: "rows",
			page: "page",
			total: "total",
			records: "records",
			repeatitems: false,
			cell: "cell",
			id: "id"      				
		}      			
	});               
	
	emp.$("grid-map-tool").jqGrid({pgbuttons:false, recordtext:''});        
	
	emp.$("#grid-map-tool").jqGrid('navGrid','#pager2', {edit:false, add:false, del:false, search:false, refresh:false},
			{}, {}, {}, { 	// search      					
				sopt:['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
				closeOnEscape: true,      					
				multipleSearch: true,
				closeAfterSearch: true                    					
			}      				
	);               
	
	emp.$("#grid-map-tool").jqGrid('gridResize',{minWidth: 300, minHeight: 250});

	emp.$("#grid-map-tool").navButtonAdd('#pager2', { 	
		caption:"",   
		title: "Reload records",      			
		buttonicon:"ui-icon-refresh",
		onClickButton: reloadMapToolGrid,
		position: "last",
		cursor: "pointer"      			
	});      		      		
	
	emp.$("#grid-map-tool").navButtonAdd('#pager2', { 	
		caption:"",      	
		title: "Add a record",		
		buttonicon:"ui-icon-plus",
		onClickButton: registerMapTool,
		position: "last",
		cursor: "pointer"      			
	});	
	
	emp.$("#grid-map-tool").navButtonAdd('#pager2', { 	
		caption:"",
		title: "Edit a record",
		buttonicon:"ui-icon-pencil",
		onClickButton: editMapTool,                   
		position: "second",
		cursor: "pointer"      			
	});	
	
	emp.$("#grid-map-tool").navButtonAdd('#pager2', { 	
		caption:"",      	
		title: "Delete a record",		
		buttonicon:"ui-icon-trash",
		onClickButton: deleteMapTool, 
		position: "third",
		cursor: "pointer"      			
	}); 
	
	emp.$("#grid-map-tool").navButtonAdd('#pager2', { 	
		caption:"",
		title: "Load a descriptor",
		buttonicon:"ui-icon-link",
		onClickButton: registerWidgetByURL, 
		position: "last",
		cursor: "pointer"      			
	});  
});          

function registerMapTool() {
	emp.$("#grid-map-tool").jqGrid('setColProp', 'id', {editrules:{required:false}} );

	// Get the currently selected row 
	emp.$('#grid-map-tool').jqGrid('editGridRow','new', {
		type: "PUT",
		url: registerMapToolUrl,
		editData: {},
		width:500,
		serializeEditData: function(data) {    
			data.id = 0;
			return emp.$.param(data);                        				
		},                   
		recreateForm: true,
		beforeShowForm: function(form) {
			emp.$('#pData').hide(); 
			emp.$('#nData').hide();
			//emp.$('#password',form).addClass('ui-widget-content').addClass('ui-corner-all');      				
		},
		beforeInitData: function(form) {},
		beforeCheckValues: function(postdata,formid,mode) {
			emp.$("#grid-map-tool").jqGrid('setColProp', 'id', {editrules:{required:false}}, {editable:false} );      				
		},
		closeAfterAdd: true,
		reloadAfterSubmit:true,
		afterSubmit : function(response, postdata) {
			var result = jQuery.parseJSON(response.responseText);
			var errors = "";					
			
			if (result.success == false) {
				for (var i = 0; i < result.message.length; i++) {
					errors +=  result.message[i] + "<br/>";      						
				}      					
			}  else {
				emp.$('#msgbox').text('Entry has been added successfully');
				emp.$('#msgbox').dialog( {	
					title: 'Success',
					modal: true,
					buttons: {
						"Ok": function()  {
							emp.$(this).dialog("close");    							      								
						}      					
					}      					
				});      					
			}
			// only used for adding new records 
			var newId = null;
			//force reloading 
			emp.$("#grid-map-tool").trigger("reloadGrid");	    	
			return [result.success, errors, newId];      				
		}      			
	});		      		
} // end of registerMapTool 

function editMapTool() {
	emp.$("#grid-map-tool").jqGrid('setColProp', 'serverUrl', 'type', {editoptions:{readonly:false, size:55}});        
	
	// Get the currently selected row 
	var row = emp.$('#grid-map-tool').jqGrid('getGridParam','selrow');
	
	if( row != null ) {	
		emp.$('#grid-map-tool').jqGrid('editGridRow', row, {
			url: editMapToolUrl,
			editData: {},
			width:500,
			recreateForm: true,
			beforeShowForm: function(form) {
				emp.$('#pData').hide(); 
				emp.$('#nData').hide();      					
			},      				
			beforeSubmit: function(postdata, formid) {
				postdata.prevServerUrl = emp.$('#grid-map-tool').jqGrid('getCell', row, 'serverUrl');
				return [true, ""];
			},
			beforeInitData: function(form) {
			},
			closeAfterEdit: true,
			reloadAfterSubmit:true,
			afterSubmit : function(response, postdata) {      					
				var result = jQuery.parseJSON(response.responseText);
				var errors = "";					
				if (result.success == false) {
					for (var i = 0; i < result.message.length; i++) {
						errors +=  result.message[i] + "<br/>";      							
					}      						
				} else {
					emp.$('#msgbox').text('Entry has been edited successfully');
					emp.$('#msgbox').dialog({
						title: 'Success',
						modal: true,
						buttons: {
							"Ok": function() {
								emp.$(this).dialog("close");     									      									
							}                                   						
						}                                  						      						
					});                                    						
				}                                                    
				
				// only used for adding new records 
				var newId = null;
				//force reloading 
				emp.$("#grid-map-tool").trigger("reloadGrid");      					
				
				return [result.success, errors, newId];                                                        					
			}    				      				
		});    			      			
	} else {
		emp.$('#msgbox').text('You must select a record first!');
		emp.$('#msgbox').dialog({      				
			title: 'Error',
			modal: true,
			buttons: {
				"Ok": function() {
					emp.$(this).dialog("close");      						
				}
			}      			
		});      			
	}      		
}

function deleteMapTool() {
	// Get the currently selected row 
	var row = emp.$('#grid-map-tool').jqGrid('getGridParam','selrow');
	var selRows = emp.$('#grid-map-tool').jqGrid('getGridParam', 'selarrrow');      		
	var stringArray = selRows;
	
	for (var i = 0; i < selRows.length; i++) {
		stringArray[i] = emp.$('#grid-map-tool').jqGrid('getCell', selRows[i], 'id');
	}
	
	// A pop-up dialog will appear to confirm the selected action
	if( row != null )
		emp.$('#grid-map-tool').jqGrid( 'delGridRow', row, {
			url: deleteMapToolUrl,      				
			recreateForm: true,
			beforeShowForm: function(form) {
				//Change title
				emp.$(".delmsg").replaceWith('<span style="white-space: pre;">' + 'Delete selected record?' + '</span>');
				//hide arrows
				emp.$('#pData').hide();      					
				emp.$('#nData').hide();              		         					
			},      				
			beforeSubmit: function(postdata, formid) {
				return [true, ""];
			},
			reloadAfterSubmit:true,
			closeAfterDelete: true,
			serializeDelData: function (postdata) {
				// send array of IDs to be removed from the source 
				return {ids: stringArray.join(",")};
			},
			afterSubmit : function(response, postdata) {
				var result = jQuery.parseJSON(response.responseText);
				var errors = "";					
				
				if (result.result == false) {
					for (var i = 0; i < result.message.length; i++) {
						errors +=  result.message[i] + "<br/>";      							
					}      						
				}  else {
					emp.$('#msgbox').text('Entry has been deleted successfully');
					emp.$('#msgbox').dialog({	
						title: 'Success',
						modal: true,
						buttons: {
							"Ok": function() {
								emp.$(this).dialog("close");      									
							}      						
						}      						
					});      						
				}                       
				
				// only used for adding new records
				var newId = null;
				//force reloading
				emp.$("#grid-map-tool").trigger("reloadGrid");        	
				
				return [result.result, errors, newId];      					
			}     				      				
		});      		
	else {
		emp.$('#msgbox').text('You must select a record first!');
		emp.$('#msgbox').dialog({	
			title: 'Error',
			modal: true,
			buttons: {
				"Ok": function() {
					emp.$(this).dialog("close");      						
				}      			
			}      			
		});      			
	}      		
}

function formRegistrationWidgetByURL() {
	// get the form values
	var urlOldNav = emp.$('#descriptorURL').val();			
	
	emp.$.ajax({
		type: "GET",
		url: descriptorDigestUrl,   
		data: "url=" + urlOldNav,
		dataType: "json",
		success: function(response) {
			/* emp.$("#grid-map-tool").trigger("reloadGrid", [{page:1}]); */
			reloadMapToolGrid();
		},
		error: function(e) {
			alert('Error: ' + e);				
		}								
	});	
}

function reloadMapToolGrid() {
	emp.$("#grid-map-tool").trigger("reloadGrid", [{page:1}]);
}     	      	      	

function registerWidgetByURL() {
	// get the form values
	emp.$("#grid-map-tool").jqGrid('setColProp', 'id', {editrules:{required:false}} );
	emp.$("#grid-map-tool").jqGrid('setColProp', 'name', {editrules:{required:false}} );
	emp.$("#grid-map-tool").jqGrid('setColProp', 'descr', {editrules:{required:false}} );
	emp.$("#grid-map-tool").jqGrid('setColProp', 'iconUrl', {editrules:{required:false}} );
	emp.$("#grid-map-tool").jqGrid('setColProp', 'displayName', {editrules:{required:false}} );
	
	// Get the currently selected row 
	var row = emp.$('#grid-map-tool').jqGrid('getGridParam','selrow');
	row = 1;
	
	if( row != null ) {	
		emp.$('#grid-map-tool').jqGrid('editGridRow', row, {
			type: "PUT",
			url: descriptorDigestUrl,   
/* 			data: "url=" + urlOldNav, */
			dataType: "json",
			width:750,
  			serializeEditData: function(data) {
  				return emp.$.param(data);                          				
  			},  
			recreateForm: true,
			beforeShowForm: function(form) {
				var descriptorRow = '<tr id="descriptorUrlInputRow" class="FormData" rowpos=0><td class="CaptionTD">Descriptor URL:</td><td id="DataTD"><input id="url" class="FormElement ui-widget-content ui-corner-all" type="text" size="80" name="url" role="textbox"></td></tr>';

				emp.$('#TblGrid_grid-map-tool tbody').append(descriptorRow);
				emp.$('#pData').hide(); 
				emp.$('#nData').hide();
				emp.$('#tr_name').hide();
				emp.$('#tr_descr').hide();      					
				emp.$('#tr_iconUrl').hide();
				emp.$('#tr_displayName').hide();     					      					      					
			},      				
			closeAfterEdit: true,
			reloadAfterSubmit:true,
			afterSubmit : function(response, postdata) {      					
				var result = jQuery.parseJSON(response.responseText);
				var errors = "";					
				if (result.success == false) {
					for (var i = 0; i < result.message.length; i++) {
						errors +=  result.message[i] + "<br/>";      							
					}      						
				} else {
					emp.$('#msgbox').text('Entry has been loaded successfully');
					emp.$('#msgbox').dialog({
						title: 'Success',
						modal: true,
						buttons: {
							"Ok": function() {
								emp.$(this).dialog("close");     									      									
							}                                   						
						}                                  						      						
					});                                    						
				}                                                    
				
				// only used for adding new records 
				var newId = null;
				//force reloading 
				emp.$("#grid-map-tool").trigger("reloadGrid");      					
				
				return [result.success, errors, newId];                                                        					
			}    				      				
		});    			      			
	} else {
		emp.$('#msgbox').text('You must select a record first!');
		emp.$('#msgbox').dialog({      				
			title: 'Error',
			modal: true,
			buttons: {
				"Ok": function() {
					emp.$(this).dialog("close");      						
				}
			}      			
		});      			
	}      		
}

   
/*
* FUNCT1ION gridLoadInit3
* This method is tied to grid loads, through the gridComplete attribute
* Any time the data is refreshed in the grid (page load, paging, manual reset, etc)
* then this method is run to set event bindings on any created DOM. We also
* use this method to re-'check' any records previously selected.
*/   		
	var gridLoadInit3 = function () {
	// if the 'selected' array has length 
	// then loop current records, and 'check' 
	// those that should be selected 
	if (selArr.length > 0) {
		var tmp = emp.$("#grid-map-tool").jqGrid('getDataIDs');
		emp.$.each(selArr, function(ind, val){
			var pos = emp.$.inArray(val, tmp);
			if (pos > -1) {
				emp.$("#grid-map-tool").jqGrid('setSelection',val);   						
			}   					
		});   				
	}
	
	emp.$('#grid-map-tool ' + 'tr').removeClass("ui-widget-content");
	emp.$('#grid-map-tool ' + 'tr:nth-child(odd)').addClass('toolsAltRow');
}; 

/*
* FUNCTION gridUnloader
* Called from within the populateGrid method, this method is to unbind
* any event handlers created during grid load, by the gridLoadInit3 method.
*/
var gridUnloader = function () {   			
};

/*
* FUNCTION selectionManager
* Used to handle selections across paging requests
*/
var selectionManager = function (id, status) {
	// was it checked (true) or unchecked (false)
	if(status) {
		// if it's just one id (not array)
		if(!emp.$.isArray(id)) {
			// if it's not already in the array, then add it
			if (emp.$.inArray(id, selArr) < 0) {
				selArr.push(id);   						
			}   					
		} else {
			// which id's aren't already in the 'selected' array
			var tmp = emp.$.grep(id, function(item,ind){
				return emp.$.inArray(item, selArr) < 0;   						
			});
			// add only those unique id's to the 'selected' array
			emp.$.merge(selArr, tmp);   					
		}   				
	} else {
		// if it's just one id (not array)
		if(!emp.$.isArray(id)){
			// remove that one id
			selArr.splice(emp.$.inArray(id, selArr), 1);   					
		} else {
			// give me an array without the 'id's passed
			// (resetting the 'selected' array)
			selArr = emp.$.grep(selArr, function(item, ind){
				return emp.$.inArray(item, id) > -1;   						
			}, true);   					
		}   				
	}		
};

/*
* FUNCTION rowSelectionHandler
* Used to handle row selections
*/
var rowSelectionHandler = function (id, status) {
	selectionManager(id, status);  			
};

/*
* FUNCTION selectAllHandler
* Used to handle selection of all records displayed
*/
var selectAllHandler = function (idArr, status) {   			
	selectionManager(idArr, status);   			
};  	